/**
 * 起重设备运行记录craneRecord.js
 * 版本号： v1.0.0
 */
$(function () {
    //获取项目id
    var prId = $('#prId_').val();

    /**
     * 时间选中事件
     */
    $("#startDate_").datebox({
        onSelect : function(beginDate){
            $('#endDate_').datebox().datebox('calendar').calendar({
                validator: function(date){
                    return beginDate<=date;
                }
            });
        }
    });

    //查询设备编号绑定
    bindCombo_deviceId("deviceId_",prId);

    /**
     *起重设备运行记录列表
     */
    var lastChecked = 0;
    $("#craneRecord_dataList").datagrid({
        fit: true,
        fitColumns: true,
        method: "POST",
        rownumbers: true,
        singleSelect: true,
        pagination: true,
        border: false,
        pageSize: 10,
        pageList: [10, 30, 50, 100],
        url: CONTEXT_PATH + '/craneRecord/craneHistoricalData.do?prId='+prId,
        idField: 'crId',
        frozenColumns: [[
            {field: 'crId', checkbox: true},
            {field: 'craneProject', title: '设备名称', width: 120,
                formatter:function(value){
                    if(value){
                        return value.cpName;
                    }
                }
            },
            {field: 'craneProject_deviceId', title: '设备编号', width: 180,
                formatter:function(value,row){
                    if(row.craneProject.deviceId){
                        return row.craneProject.deviceId;
                    }
                }
            },
            {field: 'project', title: '所属项目', width: 200,
                formatter:function(value){
                    if(value){
                        return value.prName;
                    }
                }
            }
        ]],
        columns: [
            [
                {field: 'load', title: '载重(t)', width: 45},
                {field: 'torque', title: '力矩(KN.m)', width: 55},
                {field: 'range', title: '幅度(度)', width: 45},
                {field: 'height', title: '高度(m)', width: 45},
                {field: 'windSpeed', title: '风速(级)', width: 45},
                {field: 'slewingSpeed', title: '回转(度)', width: 55},
                {field: 'rate', title: '倍率', width: 35},
                {field: 'dipAngle', title: '倾角(度)', width: 45},
                {field: 'collectTime', title: '采集时间', width: 140,
                    formatter:function(val) {
                        if(val){
                            return formatDate(val);
                        }
                    }
                }
            ]
        ],
        onCheck:function(rowIndex, rowData){
            var row = $("#craneRecord_dataList").datagrid("getChecked");
            if(row && rowIndex == lastChecked){
                $('#craneRecord_dataList').datagrid("unselectAll");//取消选中当前所有行
                lastChecked = null;
            }else{
                lastChecked = rowIndex;
            }
        },
        onLoadSuccess: function (data) {
            if (data.rows.length > 0) {
                lastChecked = null;
                $("#craneRecord_dataList").datagrid("selectRow", 0);
            }
        }
    });

    //定义可操作按钮
    $("#craneRecord_menu").dialog({
        title: '',
        width: 'auto',
        height:35,
        closed: false,
        cache: false,
        inline: true,
        modal: false,
        border: false,
        toolbar: createToolbar()
    });

});

/**
 * 创建toolbar按钮组
 * @returns {Array}
 */
function createToolbar() {
    var toolbar = [];
    var falg = false;
    for(var j = 0; j < btnOptions.length; j++ ){
        if(false != btnOptions[j].value){
            falg = true;
            break;
        }
    }
    if(!falg){
        //不存在按钮
        toolbar.push({});
    }else{
        //存在按钮
        for(var i = 0; i < btnOptions.length; i++){
            if(false != btnOptions[i].value){
                //查询按钮
                if("searchBtn"  == btnOptions[i].key){
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            craneRecord_doSearch();
                        }
                    });
                }
                //详情按钮
                if("viewBtn"  == btnOptions[i].key){
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            craneRecord_view($(this).linkbutton("options").iconCls);
                        }
                    });
                }
                //导出按钮
                if("exportBtn"  == btnOptions[i].key){
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls: "icon_export_user",
                        handler: function () {
                            craneRecord_export();
                        }
                    });
                }
            }
        }
    }
    return toolbar;
}

/**
 * 执行查询
 */
function craneRecord_doSearch() {

    $("#craneRecord_dataList").datagrid("reload", {
        deviceId:$("#deviceId_").combobox("getValue"),
        startDate: $("#startDate_").datetimebox("getValue"),
        endDate: $("#endDate_").datetimebox("getValue")

    });

    //刷新dg页码
    refreshPageNumber("craneRecord_dataList");

    $("#craneRecord_dataList").datagrid("clearSelections");
}

/**
 * 导出数据
 */
function craneRecord_export(){
    //判断没有选中数据时，无法导出
    var row = $("#craneRecord_dataList").datagrid("getSelected");
    if (row == null) {
        $.messager.show({title: '操作提示', msg: "没有数据无法导出", timeout: 3000, showType: "slide"});
        return;
    }
    //构建数据表的二维数组的DATA
    var sheetData = [];
    //每一行的数据
    var rowData = [];
    //从页面上的表格数据中获取到数据表格的所有数据，是一个二维数据结构
    var rows = $('#craneRecord_dataList').datagrid("getRows");
    //获取数据表中未冻结的所有列
    var columns = $('#craneRecord_dataList').datagrid("options").columns[0];
    //获取数据表中被冻结的所有列
    var frozenColumns = $('#craneRecord_dataList').datagrid("options").frozenColumns[0];
    //设置列表头行（描述行）
    //加载被冻结的列名
    for (var i = 0; i < frozenColumns.length; i++) {
        if(frozenColumns[i].title){
            rowData.push(frozenColumns[i].title);
        }
    }
    //加载未被冻结的列名
    for (var i = 0; i < columns.length; i++) {
        rowData.push(columns[i].title);
    }
    //将构建好的第一行描述列的数据放入二维数据表的二维数组中。
    sheetData.push(rowData);
    //遍历真实数据行
    for (var i = 0; i < rows.length; i++) {
        //将行数据置为空
        rowData = [];
        //处理列的数据，有子对象属性的做特殊处理
        for (var j = 0; j < frozenColumns.length; j++) {
            if(frozenColumns[j].field == "craneProject"){
                if (rows[i][frozenColumns[j].field] != null) {
                    var value = rows[i][frozenColumns[j].field];
                    rowData.push(value.cpName.toString());
                } else {
                    rowData.push("");
                }
            }
            if(frozenColumns[j].field == "craneProject_deviceId"){
                if (rows[i].craneProject.deviceId != null) {
                    rowData.push(rows[i].craneProject.deviceId.toString());
                } else {
                    rowData.push("");
                }

            }
            if(frozenColumns[j].field == "project"){
                if (rows[i][frozenColumns[j].field] != null) {
                    var value = rows[i][frozenColumns[j].field];
                    rowData.push(value.prName.toString());
                } else {
                    rowData.push("");
                }
            }
        }
        for (var j = 0; j < columns.length; j++) {
            if (rows[i][columns[j].field] != null) {
                rowData.push(rows[i][columns[j].field].toString());
            } else {
                rowData.push("");
            }
        }
        //一行数据加载完后往数据表格二维数组中push
        sheetData.push(rowData);
    }
    /* build worksheet from the grid data */
    var ws = XLSX.utils.aoa_to_sheet(sheetData);

    /* build up workbook */
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '导出数据');

    /* generate download */
    XLSX.writeFile(wb, "起重机械历史数据"+new Date().format("yyyy-MM-dd hh-mm-ss")+".xlsx");
}

//查询设备编号下拉框
function bindCombo_deviceId(deviceControl,prId){
    $.ajax({
        url: CONTEXT_PATH + "/craneProject/getDeviceIdList.do",
        data: {prId: prId},
        type: "get",
        success: function (data) {
            var deviceCombo = [{'text': '--请选择--', 'value': ''}];
            for (var i = 0; i < data.length; i++) {
                deviceCombo.push({"text": data[i].deviceId, "value": data[i].deviceId});
            }
            $("#" + deviceControl).combobox("loadData", deviceCombo);
        }
    })
}

/***
 * 动态刷新页面
 * @param dgId
 */
function refreshPageNumber(dgId) {
    //获取dataGrid的列表对象属性
    var $datagrid = $("#" + dgId).datagrid("options");
    if ($datagrid != undefined) {
        $datagrid.pageNumber = 1;
    }
    //获取dataGrid的分页对象
    var $getPager = $("#" + dgId).datagrid('getPager');
    var $pagination = $($getPager).pagination("options");
    if ($pagination != undefined) {
        $pagination.pageNumber = 1;
    }
}

/**
 * 查看详情
 */
function craneRecord_view(iconCls){
    var row = $("#craneRecord_dataList").datagrid("getSelected");
    if (row == null) {
        $.messager.show({ title: '操作提示', msg: "请选择需要查看的项目详情", timeout: 3000, showType: "slide" });
        return;
    }
    //IFRAM打开窗口
    layoutSub(qzlsxq.id, qzlsxq.url + row.crId, iconCls, qzlsxq.closable, qzlsxq.title);
}